import React from 'react';
import {StyleSheet, View, Linking} from 'react-native';
import Toast from 'react-native-easy-toast';

import api from '../../../common/api';
import utils from '../../../common/utils';

import Header from './header';
import Banner from './banner';
import Info from './info';
import Detail from './detail';
import Bottom from './bottom';

import FavHeader from '../../../components/favHeader';
import List from '../../../components/list';
import auth from "../../../common/auth";


export default class extends React.Component {
    state = {
        favList: [],
        isFetchingFavList: false,
        isFetchingDetail: true,
        isFetchingCollect: false,
        hasMore: true,
        bgColor: 'rgba(243,171,185,0)',
        titleColor: 'rgba(255,255,255,0)',
        itemId: 0,
        itemInfo: {},
        couponLinkTaoToken: '',
        couponShortLinkUrl: '',
        shareUrl: ''
    };
    //获取详情
    getDetail = () => {
        const {itemId} = this.state;
        api({url: 'api/item/getItemDetail', data: {num_iid: itemId}, notNeedLogin: true})
            .then(data => {
                this.setState({
                    itemInfo: data
                });
            })
            .catch(e => {
                console.log(e);
            })
            .finally(() => {
                this.setState({
                    isFetchingDetail: false
                });
            });
    };
    //获取数据
    getFavList = () => {
        const {isFetchingFavList, favList} = this.state;
        if (isFetchingFavList) {
            return;
        }
        this.setState({
            isFetchingFavList: true
        });
        api({url: 'api/item/getSuggestList', notNeedLogin: true})
            .then(data => {
                this.setState({
                    favList: [...favList, ...data]
                });
            })
            .catch(e => {
                console.log(e);
            })
            .finally(() => {
                this.setState({
                    isFetchingFavList: false
                });
            });
    };

    //list header
    headerComponent = () => {
        const {itemInfo, itemInfo: {small_images = [], pict_url}} = this.state;
        return (
            <View>
                <Banner imgList={small_images} mainPic={pict_url}/>
                <Info item={itemInfo}/>
                <Detail/>
                <FavHeader/>
            </View>
        );
    };
    //收藏
    _collect = () => {
        const {itemId, isFetchingCollect} = this.state;
        if (isFetchingCollect) {
            return;
        }
        auth.getUserInfo()
            .then(userInfo => {
                this.setState({
                    isFetchingCollect: true
                });
                api({url: 'api/item/addToCollection', data: {flag: 0, item_id: itemId, member_id: userInfo.id}})
                    .then(() => {
                        this.showToast('收藏成功');
                    })
                    .catch(e => {
                        this.showToast(e.msg);
                    })
                    .finally(() => {
                        this.setState({
                            isFetchingCollect: false
                        });
                    });
            })
            .catch(() => {
                auth.goLogin();
            });
    };
    //获取优惠券/淘口令
    getCouponInfo = () => {
        const {itemId} = this.state;
        api({url: 'api/ali/getCouponUrl', data: {itemid: itemId}})
            .then(data => {
                const {couponLinkTaoToken, couponShortLinkUrl, shareUrl} = data;
                this.setState({
                    couponLinkTaoToken,
                    couponShortLinkUrl,
                    shareUrl
                });
            })
            .catch(e => {
                this.showToast(e.msg);
            });
    };
    //跳转抢券
    linkToCoupon = () => {
        const {couponShortLinkUrl} = this.state;
        if (!couponShortLinkUrl) {
            this.showToast('券链接不存在，请重试');
            return;
        }
        Linking.canOpenURL(couponShortLinkUrl)
            .then(supported => {
                if (!supported) {
                    this.showToast('不能打开淘宝链接，请检查');
                } else {
                    return Linking.openURL(couponShortLinkUrl);
                }
            })
            .catch(err => {
                this.showToast('不能打开淘宝链接，请检查');
                console.error('An error occurred', err);
            });
    };
    //滚动事件
    onScroll = event => {
        let y = event.nativeEvent.contentOffset.y,
            opacity;
        y = y < 100 ? 100 : y >= 100 + 500 ? 100 + 500 : y;
        opacity = utils.easeInOutQuad((y - 100) / 500);
        opacity = opacity < 0 ? 0 : opacity > 1 ? 1 : opacity;
        this.setState({
            bgColor: `rgba(243,171,185,${opacity})`,
            titleColor: `rgba(255,255,255,${opacity})`
        });
    };
    //toast弹出
    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        const {params = {}} = this.props.navigation.state;
        const itemId = params.itemId;
        this.setState({
            itemId
        }, () => {
            this.getDetail();
            this.getCouponInfo();
        });
        this._didFocusSubscription = this.props.navigation.addListener(
            'didFocus',
            () => {
                if (this.state.favList.length === 0) {
                    this.getFavList();
                }
            }
        );
    }

    componentWillUnmount() {
        this._didFocusSubscription && this._didFocusSubscription.remove();
    }

    render() {
        const {favList, bgColor, titleColor, itemInfo, couponLinkTaoToken} = this.state;
        const {navigation} = this.props;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} bgColor={bgColor} titleColor={titleColor} title={itemInfo.title}/>
                <List
                    list={favList}
                    extraData={itemInfo}
                    ListHeaderComponent={this.headerComponent}
                    onScroll={this.onScroll}
                />
                <Bottom navigation={navigation}
                        collect={this._collect}
                        linkToCoupon={this.linkToCoupon}
                        showToast={this.showToast}
                        couponLinkTaoToken={couponLinkTaoToken}
                        itemInfo={itemInfo}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f6f6f5',
        flex: 1
    }
});
